//
//  tooles.m
//  huoche
//
//  Created by kan xu on 11-1-22.
//  Copyright 2011 paduu. All rights reserved.
//

#import "tooles.h"

@interface tooles()

@end

@implementation tooles

+(void)dismissGlobalAlert
{
    [APPALL.globalAlertView dismissWithClickedButtonIndex:0 animated:YES];
    APPALL.globalAlertView = nil;
}

+(void)showGlobalAlertWithTitle:(NSString*)title andMsg:(NSString*)msg delegate:(id<UIAlertViewDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles
{
    [tooles dismissGlobalAlert];
    if(otherButtonTitles == nil)
    {
        APPALL.globalAlertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
    }
    else
    {
        APPALL.globalAlertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles,nil];
    }
    [APPALL.globalAlertView show];
}

+(UIImage*)getImageByColor:(UIColor*)aColor
{
    CGSize as = CGSizeMake(1, 1);
    UIImage *img = nil;
    CGRect rect = CGRectMake(0, 0, as.width, as.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,
                                   aColor.CGColor);
    CGContextFillRect(context, rect);
    img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+(NSString*)versionArray
{
    return @"";
}

+(float)DeviceVersion
{
    return [[UIDevice currentDevice].systemVersion doubleValue];
}

+(NSDate *)dateFromString:(NSString *)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd 00:00:00"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    dateFormatter = nil;
    return destDate;
    
}

+(NSString *)stringFromDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString = [dateFormatter stringFromDate:date];
    dateFormatter = nil;
    return destDateString;
}

+ (NSString *)defaultViewControllerWithNibName:(NSString *)nibNameOrNil
{
    if(KDeviceHeight <= 480)
        return [NSString stringWithFormat:@"%@_4",nibNameOrNil];
    return nibNameOrNil;
}

+ (NSString *)nibname:(NSString *)nibNameOrNil
{
    if (KDeviceHeight <= 480) {
        //iphone 3G,4,4s
        return [NSString stringWithFormat:@"%@_4",nibNameOrNil];
    }
    return nibNameOrNil;
}

/*
 * 信用卡号验证基本算法：
 * 偶数位卡号奇数位上数字*2，奇数位卡号偶数位上数字*2。
 * 大于10的位数减9。
 * 全部数字加起来。
 * 结果不是10的倍数的卡号非法。
 */
+ (BOOL)validateCreditCard:(NSString*)iStr
{
    BOOL result = TRUE;
    NSString *value = [iStr stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [iStr length])];
    NSInteger length = [iStr length];
    if (length >= 13)
    {
        result = [tooles validateNumber:value];
        if (result)
        {
            NSInteger twoDigitBeginValue = [[value substringWithRange:NSMakeRange(0, 2)] integerValue];
            NSInteger threeDigitBeginValue = [[value substringWithRange:NSMakeRange(0, 3)] integerValue];
            NSInteger fourDigitBeginValue = [[value substringWithRange:NSMakeRange(0, 4)] integerValue];
            //Diner's Club
            if (((threeDigitBeginValue >= 300 && threeDigitBeginValue <= 305)||
                 fourDigitBeginValue == 3095||twoDigitBeginValue==36||twoDigitBeginValue==38) && (14 != length))
            {
                result = FALSE;
            }
            //VISA
            else if([value hasPrefix:@"4"] && !(13 == length||16 == length))
            {
                result = FALSE;
            }
            //MasterCard
            else if((twoDigitBeginValue >= 51||twoDigitBeginValue <= 55) && (16 != length))
            {
                result = FALSE;
            }
            //American Express
            else if(([value hasPrefix:@"34"]||[value hasPrefix:@"37"]) && (15 != length))
            {
                result = FALSE;
            }
            //Discover
            else if([value hasPrefix:@"6011"] && (16 != length))
            {
                result = FALSE;
            }
            else
            {
                NSInteger begin = [[value substringWithRange:NSMakeRange(0, 6)] integerValue];
                //CUP
                if ((begin >= 622126 && begin <= 622925) && (16 != length))
                {
                    result = FALSE;
                }
                //other
                else
                {
                    result = TRUE;
                }
            }
        }
        if (result)
        {
            NSInteger digitValue;
            NSInteger checkSum = 0;
            NSInteger index = 0;
            NSInteger leftIndex;
            //even length, odd index
            if (0 == length%2)
            {
                index = 0;
                leftIndex = 1;
            }
            //odd length, even index
            else
            {
                index = 1;
                leftIndex = 0;
            }
            while (index < length)
            {
                digitValue = [[value substringWithRange:NSMakeRange(index, 1)] integerValue];
                digitValue = digitValue*2;
                if (digitValue >= 10)
                {
                    checkSum += digitValue/10 + digitValue%10;
                }
                else
                {
                    checkSum += digitValue;
                }
                digitValue = [[value substringWithRange:NSMakeRange(leftIndex, 1)] integerValue];
                checkSum += digitValue;
                index += 2;
                leftIndex += 2;
            }
            result = (0 == checkSum%10) ? TRUE:FALSE;
        }
    }
    else
    {
        result = FALSE;
    }
    return result;
}

+ (BOOL)validatePeriodCard:(NSString*)aStr
{
    if(aStr.length != 5)
        return NO;
    NSArray *cacheArray = [aStr componentsSeparatedByString:@"/"];
    if(cacheArray.count != 2)
        return NO;
    NSString *item1 = [cacheArray firstObject];
    NSString *item2 = [cacheArray lastObject];
    if(![self validateNumber:item1])
        return NO;
    if(![self validateNumber:item2])
        return NO;
    int num1 = [item1 intValue];
    int num2 = [item2 intValue];
    if(num1 < 1 || num1 > 12)
        return NO;
    if(num2 <= 13 || num2 >= 100)
        return NO;
    return YES;
}


+(BOOL)validateNumber:(NSString*)aStr;
{
    NSString *tagStr = @"^[0-9]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
    return [carTest evaluateWithObject:aStr];
}

+(BOOL)validatePhone:(NSString*)aStr
{
    NSString *tagStr = @"^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})(-[0-9]{1,4})?$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
    return [carTest evaluateWithObject:aStr];
}

+ (BOOL)validateCreditCode:(NSString*)aStr
{
    NSMutableString *cacheStr = [NSMutableString stringWithString:aStr];
    [cacheStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [cacheStr length])];
    NSString *tagStr = @"^[0-9]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
    return [carTest evaluateWithObject:cacheStr];
}


+(BOOL)validateTelephone:(NSString*)aStr
{
    NSString *tagStr = @"^1[0-9]{10}";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
    return [carTest evaluateWithObject:aStr];
}

+(BOOL)validateUsername:(NSString*)aStr
{
    NSString *tagStr = @"^[A-Za-z0-9_]{6,20}+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
//    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:aStr];
}

+(BOOL)validateEmail:(NSString*)aStr
{
    NSString *tagStr = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
//    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:aStr];
}

+(BOOL)validatePassword:(NSString*)aStr
{
    /*
    NSString *tagStr = @"^\\w{6,20}+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
//    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:aStr];
     */
    if([aStr length] >= 6 && [aStr length] <= 20)
    {
        return YES;
    }
    return NO;
}

+(BOOL)validateChineseName:(NSString*)aStr
{
    NSString *tagStr = @"^[\u4e00-\u9fa5A-Z0-9a-z._%+-]{2,20}+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",tagStr];
//    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:aStr];
}

+(UIImage *)rotateImage:(UIImage *)aImage
{
    CGImageRef imgRef = aImage.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    CGFloat scaleRatio = 1;
    CGFloat boundHeight;
    UIImageOrientation orient = aImage.imageOrientation;
    
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(width, height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(height, width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    }
    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}

+(UIImage *)scaleImage:(UIImage *)image
{
    double sizeOrgin = image.size.width * image.size.height;
    double targetSize = 512 * 512;
    
    double scale = sqrt(targetSize/sizeOrgin);
    
    NSLog(@"scale:%f",scale);
    
    if(scale >= 1)
    {
        return [image copy];
    }
    
    int scaledWidth = (int)(image.size.width * scale);
    int scaleHeight = (int)(image.size.height * scale);
    
    UIGraphicsBeginImageContext(CGSizeMake(scaledWidth,scaleHeight));
    [image drawInRect:CGRectMake(0, 0,scaledWidth,scaleHeight)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+(NSString*)replaceNullFromDic:(NSDictionary*)aDic withKeyArray:(NSArray*)aArray
{
    NSString *answerStr = @"";
    NSInteger arrlen = aArray.count - 1;
    NSDictionary *cacheDic = aDic;
    for(int i = 0; i <= arrlen; i++){
        if(i < arrlen){
            cacheDic = [cacheDic objectForKey:[aArray objectAtIndex:i]];
            if([cacheDic isEqual:[NSNull null]]){
                return @"";
            }
            if(!cacheDic){
                return @"";
            }
        }else{
            answerStr = [cacheDic valueForKey:[aArray objectAtIndex:i]];
            if([answerStr isEqual:[NSNull null]]){
                return @"";
            }
        }
    }
    return answerStr;
}

+(void)orderButtons:(NSArray*)butArray byCode:(NSInteger)code{
    UIButton *but1 = [butArray objectAtIndex:0];
    UIButton *but2 = [butArray objectAtIndex:1];
    UIButton *but3 = [butArray objectAtIndex:2];
    /*
     ************************************************************
     {"code":100,"name":"编辑","description":null,"id":1},
     {"code":200,"name":"已生成","description":null,"id":2},
     {"code":300,"name":"已预付","description":null,"id":3},
     {"code":-200,"name":"不完整失效","description":null,"id":4},
     {"code":-300,"name":"付款超时失效","description":null,"id":5},
     {"code":400,"name":"服务完成","description":null,"id":6},
     {"code":550,"name":"理发师已评","description":null,"id":8},
     {"code":500,"name":"顾客已评","description":null,"id":7},
     {"code":600,"name":"双方已评","description":null,"id":9}
     {"code":-400,"name":"申请退款","description":null,"id":10},
     {"code":-500,"name":"退款已完成","description":null,"id":11},
     {"code":-900,"name":"订单取消","description":null,"id":12},
     
     已预付——确认服务+申请退款+查看详情——确认服务之后进入
     历史账单：查看详情+评价（如果未评价，6天后自动回复）
     申请退款：在我的预约里，查看详情+退款中——退款成功之后进入历史订单+查看详情
     未支付——取消订单+查看详情+付款
     1、如果取消订单，进入历史订单+查看详情
     2、如果付款了，进入支付流程。。。。。。
     */
    but1.hidden = NO;
    but2.hidden = NO;
    but3.hidden = NO;
    switch (code) {
        case 100:
        case -200:
        case -300:
        case -900:
            but1.hidden = YES;
            but2.hidden = YES;
            but3.hidden = YES;
            break;
        case 200:
            [but1 setTitle:@"支付订单" forState:UIControlStateNormal];
            [but2 setTitle:@"查看详情" forState:UIControlStateNormal];
            [but3 setTitle:@"取消订单" forState:UIControlStateNormal];
            break;
        case 300:
            [but1 setTitle:@"确认服务" forState:UIControlStateNormal];
            [but2 setTitle:@"查看详情" forState:UIControlStateNormal];
            [but3 setTitle:@"申请退款" forState:UIControlStateNormal];
            break;
        case 400:
        case 550:
            [but1 setTitle:@"评价订单" forState:UIControlStateNormal];
            [but2 setTitle:@"查看详情" forState:UIControlStateNormal];
            but3.hidden = YES;
            break;
        case 500:
        case 600:
        case -400:
        case -500:
            [but1 setTitle:@"查看详情" forState:UIControlStateNormal];
            but2.hidden = YES;
            but3.hidden = YES;
            break;
        default:
            but1.hidden = YES;
            but2.hidden = YES;
            but3.hidden = YES;
            break;
    }
}

@end
